<template>
	<div class="publicNav">
		<div class="w1200" :class="(productType=='qwvedio'||productType=='qwvediotf')?'w1024':''">
			<div class="mysmnav" :class="isIE11?'':'not-ie11'">
				<span v-if="showNav" @click="toHome" :class="menuIndex==0?'selected-menu':''" class="link">首页</span>
				<template v-for="(item,index) in routeList">
					<p class="link" v-if="item.meta.out" @click="clickCount('首页菜单',item.meta.title,baseUrl+item.path)" :class="menuIndex==index+1?'selected-menu':''" :key="item.name">{{item.meta.title}}
						<img class="notice-tag" v-if="(item.meta.title=='业务公告'||item.meta.title=='平台公告')&&messageProduct&&messageProduct==productType" src="../assets/images/new_notice.svg"/>
					</p>
					<template v-else>
						<router-link class="link" v-if="(!item.meta.hide&&item.name!='Audit')||(!item.meta.hide&&item.name=='Audit'&&level>1)" :class="menuIndex==index+1?'selected-menu':''" @click.native="tap(index);clickCount('首页菜单','个人中心')" :key="item.name" :to="item.path">
							{{item.meta.title}}
							<img class="notice-tag" v-if="(item.meta.title=='业务公告'||item.meta.title=='平台公告')&&messageProduct&&messageProduct==productType" src="../assets/images/new_notice.svg"/>
							<div class="wait-pay-count" v-if="item.name=='OrderManage'&&waitPayCount">{{waitPayCount}}个未支付</div>
							<div class="wait-audit-count" v-if="item.name=='Audit'&&waitAuditCount">{{waitAuditCount}}</div>
						</router-link>
					</template>
				</template>
				<span v-if="!showNav" @click="goBack" class="link">返回上一页</span>
			</div>
			<div class="tools" v-if="routeName=='VideoRingPoster'">
				<div class="nav-right" :class="showTools?'hover':''">
					<div @click="showTools=!showTools" class="nav-right-inner flex flex-align-center flex-justify-center">
						<img src="../assets/images/newTop/tools.png" class="nav-icon">
						<span>工具箱</span>
						<span class="nav-arrow"></span>
					</div>
					<div v-if="showTools" class="nav-menu-list">
						<a style="text-align: left;" :href="baseUrl+'/companyringweb/goringlist?typeflag=1'" class="nav-menu">铃音查询</a>
						<a style="text-align: left;" :href="baseUrl+'/channel/companyringweb/zhonggao/list?typeflag=1'" class="nav-menu">用户信息查询</a>
						<a style="text-align: left;" download href="https://img.xnhkfpt.com/lvdata/file/uploadFiles/qwvedio/视频彩铃审核标准.docx" class="nav-menu">视频彩铃审核标准</a>
					</div>
				</div>
				<div class="nav-right" style="width:90px;">
					<a style="width:110px;" :href="baseUrl+'/companyringweb/postcircle/list?typeflag=1'" class="nav-right-inner flex flex-align-center flex-justify-center">
						<img src="../assets/images/newTop/dx.png" class="nav-icon">电信提单
					</a>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import * as routes from '@/router/modules'
	import { baseUrl, setCookie, getCookie, deepClone,getBrowserType} from '@/utils/common'

	export default {
		data() {
			let that=this
			return {
				isIE11:getBrowserType()=='IE 11',
				baseUrl,
				level:'',
				showNav: true,
				showTools: false,
				routeList: [],
				menuList: [],
				menuIndex: 0,
				
				websocketpush:null,
				lockReconnect:false,  //避免ws重复连接
				websocketuser:"",
				shwotiteflag:false,
				shwotitetitle:"",
				shwotitetitleold:document.title,
				heartCheck:{
			        timeout: 30000,        //1分钟发一次心跳
			        timeoutObj: null,
			        serverTimeoutObj: null,
			        reset: function () {
			            clearTimeout(this.timeoutObj);
			            clearTimeout(this.serverTimeoutObj);
			            return this;
			        },
			        start: function () {
			            var self = this;
			            this.timeoutObj = setTimeout(function () {
			                //这里发送一个心跳，后端收到后，返回一个心跳消息，
			                //onmessage拿到返回的心跳就说明连接正常
			            	that.websocketpush.send('{\'dotype\':\'ping\',\'usertype\':\'seller\'}');
			                self.serverTimeoutObj = setTimeout(function () {
			                    //如果超过一定时间还没重置，说明后端主动断开了
			                    //如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
			                	that.websocketpush.close();  
			                },self.timeout)
			            },this.timeout)
			        }
			    },
			    shwotite:{
			        timeouttitle: 1000, 
			        timeoutObjtitle: null,
			        timeflagtitle : false,
			        reset: function () {
			        	clearInterval(this.timeoutObjtitle);
			            return this;
			        },
			        start: function () {
			        	var self = this;
			            this.timeoutObjtitle = setInterval(function () {
			            	if(self.timeflagtitle){
			            		document.title = "【　　　 】";
			            		self.timeflagtitle = false;
			            	}else{
			            		document.title = "【新消息】"+that.shwotitetitle;
			            		self.timeflagtitle = true;
			            	}
			            },self.timeouttitle);
			        }
			    },
			}
		},
		watch: {
			"$route": {
				deep: true,
				immediate: true,
				handler() {
					var routeName = this.$route.name
					var producttype = 'home'
					for(var key in routes) {
						if(key != 'default') {
							checkProduct(routes[key])
						}
					}

					function checkProduct(list) {
						list.forEach((item) => {
							if(item.name == routeName) {
								producttype = key
							}
							if(item.children && item.children.length) {
								checkProduct(item.children)
							}
						})
					}
					sessionStorage.setItem('producttype', producttype)
					this.$store.commit('setProductType', producttype)
					this.getMenuList()
				}
			},
			productType: {
				deep: true,
				immediate: true,
				handler() {
					this.routeChange()
				}
			},
			user: {
				deep: true,
				immediate: true,
				handler() {
					this.routeChange()
				}
			},
		},
		computed: {
			routeName() {
				return this.$route.name
			},
			waitPayCount() {
				return this.$store.state.waitPayCount
			},
			waitAuditCount() {
				return this.$store.state.waitAuditCount
			},
			productType() {
				return this.$store.state.producttype
			},
			user() {
				if(this.$store.state.user){
					this.level=this.$store.state.user.crmLevel
					this.createWebSocketPush(this.$store.state.user.buyerid);
				}
				return this.$store.state.user
			},
			messageProduct(){
				return this.$store.state.messageProduct
			}
		},
		async mounted() {
			this.$store.commit('setWaitPayCount')
			this.$store.commit('setWaitAuditCount')
			this.getMenuList()
			window.onbeforeunload = function () {
			    this.websocketpush.close();
			}
			if(this.productType=='home'){
				this.getNoticeDialog()
			}
			if(this.productType=='hangup'){
				this.showNoticeDialog()
			}
		},
		methods: {
			//查询挂机短信是否有未读消息
			showNoticeDialog() {
				this.$request.queryNoticeDialog({
					pagenow: 1,
					shownum: 10000,
					producttypeid: 23,
					noticetype: 2,
				}).then(res => {
					if(res.code == 0) {
						var list = res.list
						if(list.length){
							this.$store.commit('setMessageProduct','hangup')
							this.$store.commit('setMessageType',list[0].type)
						}else{
							this.$store.commit('setMessageProduct','')
							this.$store.commit('setMessageType','')
						}
					} else {

					}
				})
			},
			//弹窗公告列表
			getNoticeDialog() {
				this.$request.homeNoticeDialog({
					pagenow: 1,
					shownum: 10,
				}).then(res => {
					if(res.code == 0) {
						var list = res.noticelist || []
						if(list.length){
							this.$store.commit('setMessageProduct','home')
						}else{
							this.$store.commit('setMessageProduct','')
						}
					} else {

					}
				})
			},
			clickCount(bigmodelname,modelname,link){
				if(['Home','UserInfo','Coupon'].indexOf(this.$route.name)>-1){
					console.log(bigmodelname,modelname)
					this.$request.addHomePV({
						bigmodelname,
						modelname,
					}).then(res=>{
						if(link){
							location.href=link
						}
					}).catch(()=>{
						if(link){
							location.href=link
						}
					})
				}else{
					if(link){
						location.href=link
					}
				}
			},
			getMenuList() {
				this.$request.queryMenuInfo({
					productflag: sessionStorage.getItem('producttype')
				}).then(res => {
					if(res.code == 0) {
						this.menuList = res.objlist ? res.objlist : []
						this.routeChange()
					}
				})
			},
			routeChange() {
				const producttype = sessionStorage.getItem('producttype')
				this.routeList = deepClone(routes[producttype])
				if(producttype != 'home') {
					for(var i = 0; i < this.routeList.length; i++) {
						var flag = false
						this.menuList.forEach(menu => {
							if(menu.menuName == this.routeList[i].meta.title) {
								flag = true
							}
						})

						if(!flag && !this.routeList[i].meta.parent) {
							this.routeList.splice(i, 1)
							i--
						}
					}
				}

				if(producttype == 'hangup' && this.user.userRoleBasic == 1) {
					this.showNav = false
					this.routeList = [{
						path: '/pricemanage',
						name: 'PriceManage',
						meta: {
							title: "价格管理",
						},
						component: () =>
							import("@/pages/hangupMessage/PriceManage"),
					}]
				}

				if(producttype == 'home' && this.routeList[0]) {
					this.routeList[0].meta.title = this.user.userRole == 1 ? '员工管理' : '渠道管理'
				}
				this.routeList.forEach((route, index) => {
					if(!route.meta || route.meta.hide != true) {
						this.$route.matched.forEach(matchedRoute => {
							if(route.name == matchedRoute.name && route.name != 'Index') {
								this.menuIndex = index + 1
							}
						})
						if(route.name && route.name == this.$route.meta.parent) {
							this.menuIndex = index + 1
						}
					}
				})
			},
			tap: function(index) {
				if(this.menuIndex == index + 1) {
					return
				}
				this.menuIndex = index + 1
			},
			goBack() {
				window.location.href = "http://xnhloc.xnhkfpt.com/qudao/companyringweb/user/index?showtopjsp=xnh"
			},
			toHome() {
				this.menuIndex = 0
				var token = getCookie('token')
				if(this.$route.name=='Poster'&&this.$parent.$refs.page.searchData.productType){
					location.href = baseUrl + '/static/vue_project/index.html?fromposter=true&producttype=hangup&token=' + token + '&pwdpower=2#/home'
				}else{
					location.href = baseUrl + '/static/vue_project/index.html?producttype=hangup&token=' + token + '&pwdpower=2#/home'
				}
				
			},
			initEventHandle() {
				this.websocketpush.onopen = ()=>{
					//连接成功
					this.websocketpush.send('{\'dotype\':\'user_join\',\'usertype\':\'seller\',\'user\':\''+this.websocketuser+'\'}');
				}
				this.websocketpush.onerror = ()=> {
					//连接失败
					//alert("连接出错");
					this.shwotite.reset();
					this.reconnect();
				}
				this.websocketpush.onclose = ()=> {
					//连接断开
					//	alert("连接断开");
						this.shwotite.reset();
						this.reconnect();
						
					}
				this.websocketpush.onmessage = message=>{
					 this.heartCheck.reset().start();
					var message = JSON.parse(message.data);
					var typeflag = message.typeflag;
					var type = message.msg;
					if(typeflag){
						var messageProduct=typeflag.replace('videonotice','qwvedio').replace('notice','')
						this.$store.commit('setMessageProduct',messageProduct)
					}
					if(type&&/^\d$/.test(type)){
						this.$store.commit('setMessageType',type)
					}
				}
			},
			createWebSocketPush(userId){
				var url = encodeURI('wss://xnhws.xnhkfpt.com');
				this.websocketuser = userId;
				//var url = encodeURI('wss://xnhws.xnhkfpt.com');
				 try {
			         if ('WebSocket' in window) {
			        	 this.websocketpush = new WebSocket(url);
			         } else if ('MozWebSocket' in window) {
			        	 this.websocketpush = new MozWebSocket(url);
			         } else {
			                 //alert("您的浏览器不支持websocket协议,建议使用新版谷歌、火狐等浏览器，请勿使用IE10以下浏览器，360浏览器请使用极速模式，不要使用兼容模式！");
			         }
			         this.initEventHandle();
			     } catch (e) {
			    	 this.reconnect();
			     }
			},
			reconnect() {
			    if (this.lockReconnect) return;
			    this.lockReconnect = true;
			    setTimeout(()=>{    //没连接上会一直重连，设置延迟避免请求过多
			    	this.createWebSocketPush(this.websocketuser);
			        this.lockReconnect = false;
			    }, 2000);
			}
		}
	}
</script>

<style scoped lang="scss">
	.publicNav {
		width: 100%;
		height: 48px;
		background: #fff;
		.text-left {
			padding-left: 160px;
		}
		.w1200 {
			@include flex;
			justify-content: space-between;
		}
		.mysmnav {
			margin: 0 auto;
			text-align: center;
			@include flex;
			flex-grow: 1;
			width: 100%;
			justify-content: center;
			.link {
				font-size: 16px;
				color: #333333;
				height: 48px;
				line-height: 48px;
				flex-grow: 1;
				min-width: 80px;
				
				cursor: pointer;
				position: relative;
				display:block;
				.notice-tag{
					position: absolute;
					width: 32px;
					height: 16px;
					left: 50%;
					transform: translateX(32px);
					top: 5px;
				}
				.wait-pay-count {
					width: 84px;
					height: 16px;
					background: #FF0000;
					border-radius: 10px;
					text-align: center;
					line-height: 16px;
					color: #fff;
					font-weight: bold;
					font-size: 12px;
					position: absolute;
					left: 35px;
					top: 0px;
					&:after {
						display: block;
						content: '';
						width: 0;
						height: 0;
						border-top: 4px solid #FF0000;
						border-left: 5px solid transparent;
						border-right: 5px solid transparent;
						position: absolute;
						left: 0;
						right: 0;
						bottom: -4px;
						margin: 0 auto;
					}
				}
			}
			.selected-menu {
				color: #F39800;
			}
		}
		.not-ie11{
			.link{
				max-width: 180px;
			}
		}
		.ring {
			justify-content: flex-start;
			.link {
				width: 110px;
			}
		}
		.tools {
			margin-left: 30px;
			@include flex;
			.nav-right {
				width: 136px;
				height: 48px;
				color: #666;
				position: relative;
				cursor: pointer;
				float: left;
				.nav-right-inner {
					width: 136px;
					height: 48px;
					font-size: 14px;
					color: #666;
					.nav-icon {
						width: 20px;
						margin-right: 8px;
					}
					.nav-arrow {
						width: 0;
						height: 0;
						border-top: 6px solid #666;
						border-left: 6px solid transparent;
						border-right: 6px solid transparent;
						margin-left: 10px;
					}
					.nav-right.hover .nav-arrow {
						border-top: none;
						border-bottom: 6px solid #17A9FF;
					}
				}
				.nav-menu-list {
					width: 100%;
					background: #FFFFFF;
					border: 1px solid #EEEEEE;
					box-shadow: 3px 3px 5px rgba(51, 51, 51, 0.2);
					position: absolute;
					left: 0;
					top: 38px;
					padding: 9px 11px;
					display: none;
					.nav-menu {
						display: block;
						line-height: 36px;
						font-size: 14px;
						color: #333;
						text-decoration: none;
						&:hover {
							color: #17A9FF;
						}
					}
				}
			}
			.hover {
				.nav-menu-list {
					display: block;
				}
				.nav-arrow {
					border-top: none!important;
					border-bottom: 6px solid #17A9FF;
				}
			}
			.nav-right.hover,
			.nav-right:hover,
			.nav-right:hover .nav-right-inner,
			.nav-right a:hover {
				color: #17A9FF;
				text-decoration: none;
			}
		}
		.wait-audit-count{
			padding: 0 4px;
			min-width: 16px;
			height: 16px;
			border-radius: 8px;
			background: red;
			text-align: center;
			color: #fff;
			line-height: 16px;
			font-size: 12px;
			position: absolute;
			top: 3px;
			right: 64px;
		}
	}
</style>